import { isBoolean } from '@/utils/is';
import { cloneDeep } from 'lodash-es';
import type { Ref } from 'vue';
import { ref, unref, watch, computed } from 'vue';
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '../constant';
import { PaginationProps } from '../types/pagination';
import { BasicTableProps } from '../types/table';

export function usePagination(propsRef: Ref<BasicTableProps>) {
	const paginationRef = ref<PaginationProps | boolean>({});
	const showPaginationRef = ref(true);

	watch(
		() => unref(propsRef).pagination,
		pagination => {
			if (pagination === false) {
				paginationRef.value = false;
			}

			if (pagination && !isBoolean(pagination)) {
				paginationRef.value = pagination;
			}
		},
		{
			immediate: true,
		},
	);

	const getPaginationRef = computed((): PaginationProps | boolean => {
		const pagination = cloneDeep(unref(paginationRef));

		if ((isBoolean(pagination) && !pagination) || !unref(showPaginationRef)) {
			return false;
		}

		return {
			current: 1,
			pageSize: PAGE_SIZE,
			defaultPageSize: PAGE_SIZE,
			pageSizeOptions: PAGE_SIZE_OPTIONS,
			showSizeChanger: false,
			showTotal: total => `总计${total}条`,
			...(isBoolean(pagination) ? {} : pagination),
		};
	});

	function setPagination(info: Partial<PaginationProps>) {
		const pagination = unref(getPaginationRef);

		if (pagination === false) {
			paginationRef.value = false;
		} else {
			paginationRef.value = {
				...(isBoolean(pagination) ? {} : pagination),
				...info,
			};
		}
	}
	function getPagination() {
		return unref(getPaginationRef);
	}
	function setShowPagination(val: boolean) {
		showPaginationRef.value = val;
	}

	function getShowPagination() {
		return unref(showPaginationRef);
	}

	return {
		getPaginationRef,
		setShowPagination,
		setPagination,
		getPagination,
		getShowPagination,
	};
}
